import React, { useState, useEffect, useRef } from "react";
import { Popconfirm, Button, Tag, message } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { LeftOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import ProForm, { ModalForm, ProFormText } from "@ant-design/pro-form";
import { history, useLocation } from "umi";
import useCommonTable from "@/hooks/useCommonTable";
import {
  fetchGroupList,
  addGroup,
  createGroupNo,
  removeGroup,
  validAuditStatus,
  fetchStorageBooks,
} from "@/api/package";
import { disableStatusOptions, filterRasCode } from "@/const";
import useUpdateStatus from "@/hooks/useUpdateStatus";
import { updateStatus } from "@/api/group";

export default () => {
  const actionRef = useRef();
  const { id, specId, type } = useLocation().query;
  const renderStorageBooksModal = (record, item) => {
    const columns = [
      {
        title: "书籍芯片码",
        dataIndex: "storageBookRasCode",
        colSize: 2,
        formItemProps: (form) => {
          return {
            onChange: (e) => {
              const bagCode = filterRasCode(e.target.value);
              form.setFieldsValue({
                bagCode,
              });
            },
          };
        },
        fieldProps: {
          placeholder: "输入芯片码或扫码/感应芯片搜索",
        },
      },
    ];
    return (
      <ModalForm
        key={item.id}
        layout="horizontal"
        title="查看详情"
        submitter={false}
        trigger={
          <Tag style={{ cursor: "pointer" }} color="blue">
            {item.bagCode}
          </Tag>
        }
      >
        <ProTable
          columns={columns}
          options={false}
          request={async (params) => {
            const res = await fetchStorageBooks({
              ...params,
              id: item.id,
            });
            return {
              data: res.data?.bagBooks || [],
            };
          }}
          pagination={false}
        ></ProTable>
      </ModalForm>
    );
  };
  const columns = [
    {
      title: "分组编码",
      dataIndex: "groupNo",
    },
    {
      title: "是否启用",
      dataIndex: "status",
      valueType: "select",
      width: 200,
      fieldProps: {
        options: disableStatusOptions,
      },
      search: false,
      render: (_, record) => {
        return useUpdateStatus(
          updateStatus,
          record,
          actionRef,
          null,
          false,
          "status",
        );
      },
    },
    {
      title: "书包号",
      dataIndex: "groupNo",
      search: false,
      render: (_, record) => {
        return record?.schoolbagList?.map((item) =>
          renderStorageBooksModal(record, item)
        );
      },
    },
  ];
  const renderFormItem = () => {
    return (
      <>
        <ProFormText label="type" hidden name="type" />
        <ProFormText label="id" hidden name="categoryId" />
        <ProFormText label="规格id" hidden name="specId" />

        <ProFormText
          labelCol={{ span: 4 }}
          label="分组编码"
          disabled
          name="groupNo"
        />
      </>
    );
  };
  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            分组管理
          </div>
        ),
        breadcrumb: {},
      }}
    >
      {useCommonTable({
        actionRef,
        title: "分组",
        params: {
          categoryId: id,
          specId,
        },
        columns,
        modalWidth: 700,
        fetchList: fetchGroupList,
        add: addGroup,
        renderEdit: (record) => {
          return (
            <>
              {record?.schoolbagList?.length ? (
                <Button
                  onClick={async () => {
                    history.push(
                      `/package/index/group/addPackage?categoryId=${id}&groupId=${record.id}&specId=${specId}&edit=1`
                    );
                  }}
                >
                  编辑书包
                </Button>
              ) : (
                <Button
                  type="primary"
                  onClick={async () => {
                    const res = await validAuditStatus({
                      id: record.id,
                    });
                    if (res.data) {
                      history.push(
                        `/package/index/group/addPackage?categoryId=${id}&groupId=${record.id}&specId=${specId}`
                      );
                    } else {
                      message.warning(
                        "当前书包在RSA系统尚未审核通过，无法进行新增书包操作"
                      );
                    }
                  }}
                >
                  新增书包
                </Button>
              )}
            </>
          );
        },
        onAdd: async (formRef) => {
          const res = await createGroupNo({
            type,
          });
          if (res.data) {
            formRef.current.setFieldsValue({
              groupNo: res.data,
              categoryId: id,
              type,
              specId,
            });
          }
        },
        renderFormItem,
        remove: removeGroup,
        layout: "horizontal",
        actionColumnWidth: 200,
        showCheckbox: false,
      })}
    </PageContainer>
  );
};
